<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\GoodsDetail;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\model\AdmPhotoTag;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\DevidePackage\PackageRelatedInfo;
use Doraemon\model\ImageTagging\PredictImages;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\service\Content\ContentLabel;
use Doraemon\service\Content\ContentRelatedCategory as sContentRelatedCategory;
use Doraemon\service\Content\ContentRelatedLabel as ContentRelatedLabel;
use Doraemon\service\DecorationTask\Read;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Frieza\Modules\Photo\Extensions\Filter as SearchFilter;
use Illuminate\Http\Request;
use Doraemon\service\Photos;
use Doraemon\model\AdmPicTags;
use Encore\Admin\Widgets\Form;
use Doraemon\model\admTag;
use Doraemon\cache\Queue;
use Encore\Admin\Layout\Row;
use Doraemon\service\Tag;
use Illuminate\Support\MessageBag;
use Doraemon\model\PicStickers;
use Doraemon\model\Member;
use Doraemon\model\AdmUserType;
use Doraemon\model\WordEmbedding\KeywordScoreSearchRelation;
use Doraemon\model\WordEmbedding\KeywordObjectRelationVtwo;
use Doraemon\model\DevidePackage\UserPackage;
use Doraemon\tools\Log;
use Biz\cache\PhotoRelaGoodsIds;
use Biz\cache\PhotoRelaBaseGoods;
use Doraemon\model\NewTag\Tag as dbTag;

class PhotoNoteLabelController extends Controller
{
    const PAGE_SIZE = 20;

    const LOG = '/tmp/tag.log';

    const FILTER_ADMIN_ID_FOR_PIC_NUM = '/home/adm_rsync_dir/filter_admin_id_for_pic_num.txt';
    const TAG_MOULDS = '/home/adm_rsync_dir/tags_moulds.txt';

    const CENTER_FILE = '/home/adm_rsync_dir/center_tags.json';
    const ATTR_FILE = '/home/adm_rsync_dir/attr_tags.json';
    const ADM_TAGS_ALL = '/home/adm_rsync_dir/tags/adm_tags_all';

    const CENTER_FILE_2_0 = '/home/adm_rsync_dir/center_tags_2_0.json';
    const ATTR_FILE_2_0 = '/home/adm_rsync_dir/attr_tags_2_0.json';

    public function index(Request $request, Content $content)
    {
        $searchResult = SearchFilter::getSearchResultByParams($request);
        $total = $searchResult['total'];
        $pic_num = $searchResult['pic_num'] ?? 0;
        $ids = $searchResult['rows'];
//        $ids =['000d9tp00005c7mb','000d9tq00000098d','000d9tr00000098d'];
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息

        // 获取装修日记
        $diaryList = $diaryIds  = [];
        foreach ($photos as $photo) {
            if($photo['type'] == dbPhoto::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
        }

        if($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }

        //获取单图标签
        $show_type_map = array_column($photos, 'show_type', 'id');
        $noteIdList = $videoIdList = [];
        foreach ($show_type_map as $objId => $show_type) {
            if($show_type == dbPhoto::SHOW_TYPE_VIDEO) {
                $videoIdList[] = $objId;
            } else {
                $noteIdList[] = $objId;
            }
        }
        //获取内容的标签
        $contentLabel = [];
        $categoryList = [];
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey();
        if ($ids) {
            $contentLabel = ContentRelatedLabel::getLabelByIds($ids);
            $categoryList = sContentRelatedCategory::getTypesByObjIds($ids);
        }
        // 获取note关联的wiki
        $wiki_map = Photos::getWikiListMapByIds($ids);
        $videoTags = $videoIdList ? AdmPhotoTag::getRelInfosByIds($videoIdList) : [];
        $picTags = $noteIdList ? AdmPicTags::getRelInfosByIds($noteIdList) : [];

        $pic_ids = array_column($photos, 'pic_list');
        $pic_ids_new = [];
        if($pic_ids && is_array($pic_ids)) {
            foreach($pic_ids as $pic_json) {
                if(isset($pic_json) && $pic_json) {
                    $pic_ids_new[] = implode(',', array_column(json_decode($pic_json, true), 'pic_id'));
                }
            }
        }
        $pic_ids_new_str = implode(',', $pic_ids_new);
        $pic_ids_new_arr = explode(',', $pic_ids_new_str);

        $pic_ids = empty($photos) ? [] : $pic_ids_new_arr;

        //算法图片标签
        $tagMap = empty($pic_ids) ? [] : PredictImages::getRobotLabel($pic_ids);
        //算法文本标签
        $tagMapWord = empty($pic_ids) ? [] : KeywordObjectRelationVtwo::getByObjIds($ids);
        $tagMapWord = $this->formatTags($tagMapWord);
        //标签模板
        $moulds = [];
        if(file_exists(self::TAG_MOULDS)) {
            $moulds = json_decode(file_get_contents(self::TAG_MOULDS), true);
        }

        $i = 1;
        foreach ($photos as &$info) {
            $info['photo_id'] = $info['id'];
            $info['id'] = $i;

            if($info['type'] == dbPhoto::TYPE_DIARY) {
                $info['title'] = $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo, $wiki_map[$info['photo_id']]['list']);
            } else {
                $picInfos = json_decode($info['pic_list'], true) ?: [];
                $info['expand'] = $this->_getPicExpand($picInfos, $wiki_map[$info['photo_id']]['list']);
            }
            $info['expand'] .= $this->_getDivLine();
            $categoryFirstId = 0;
            $categorySecondId = 0;
            if (isset($categoryList[$info['photo_id']])) {
                $cateInfo = $categoryList[$info['photo_id']];
                $categoryFirstField = 'category_first_id';
                $categorySecondField = 'category_second_id';
                if ($cateInfo['source'] == 1) {//机器
                    $categoryFirstField = 'machine_category_first_id';
                    $categorySecondField = 'machine_category_second_id';
                }
                $categoryFirstId = $categoryList[$info['photo_id']][$categoryFirstField];
                $categorySecondId = $categoryList[$info['photo_id']][$categorySecondField];
            }
            $info['category_first_name'] = $categoryLabelAll[$categoryFirstId] ?? '';
            $info['category_second_name'] = $categoryLabelAll[$categorySecondId] ?? '';
            $i++;
        }
        $options = [
            'perPage' => $request->input('per_page') ? : 20,
        ];

        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($contentLabel,$categoryLabelAll) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();

            $grid->tools(function ($tools) {
                $tools->append("<a href='mouldList' class='btn btn-sm btn-success' style='float: right;'>
<i class='fa fa-save'>&nbsp;&nbsp;编辑标签模板</i></a>");
            });

            $grid->filter(function (Grid\Filter $filter) {
                SearchFilter::getFilter($filter);
            });

//            $grid->column('photo_id', 'ID')->display(function() {
//                return "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >".$this->photo_id."</a>";
//            })->width(100);
            $grid->column('photo_id', 'NOTE_ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('addtime', '额外信息')->display(function() {
                $labelLog = "<a href='/admin/devidepackage/note-label-log?&note_id=$this->photo_id' target='_blank' >打标签日志</a><br>";
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                if ($this->topic_activity_id) {
                    return $labelLog."内容主体：话题 <br>话题id：" . "<a href='http://manage.haohaozhu.me/Admin/Question/questionListNew/menuid/1012.html?id=$this->topic_activity_id' target='_blank' >" . $this->topic_activity_id . "</a>" . '<br>' . "话题标题：" . $this->topic_info['title'] . "<br>发布时间：$addtime";
                } else if($this->type == dbPhoto::TYPE_DIARY) {
                    return $labelLog."内容主体：装修日记 <br> 日记id：{$this->task_id} <br>发布时间：{$addtime}";
                } else {
                    return $labelLog."内容主体：图片<br>发布时间：$addtime";
                }
            })->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . str_replace(' ', '&nbsp;', nl2br($this->remark));
            })->width(350);
            $grid->column('admin_tag', 'admin_tag')->width(200);
            $grid->column('category', '品类')->display(function() {
                $first = empty($this->category_first_name) ? '' : "一级：{$this->category_first_name}";
                $second = empty($this->category_second_name) ? '' : "二级：{$this->category_second_name}";
                return $first . '<br>' . $second;
            })->width(100);
            $grid->column('content_label', '打标签')->display(function () use ($contentLabel) {
                $dataId = isset($contentLabel[$this->photo_id]) ? $contentLabel[$this->photo_id] : [];
                $dataId = json_encode($dataId);
                return "<div id={$this->photo_id} class='content-label' data-id={$dataId}></div>";
            });
        });

        Admin::script($this->imgScript());
        Admin::script($this->labelScript());


        //判断管理员id
        $filter_admin_ids = (array) $this->getAdminIdFilterPicNum();
        $pic_num_all_str = '';
        $pic_num_curr_str = '';
        $pic_num_curr = count($pic_ids);
        if(!in_array(Admin::user()->id, $filter_admin_ids)) {
            $pic_num_all_str = "| 图片数：$pic_num(<span style='color:red;'>仅可见筛选时间段小于7天的图片数</span>)";
            $pic_num_curr_str = "| 本页图片数：$pic_num_curr";
        }

        return $content
            ->header('note打标签')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);

    }
    //获取所有的内容标签
    public function labelList()
    {
        $data = ContentLabel::getListFormat();
        return response()->json([
            'code' => 1,
            'data' => $data
        ]);
    }
    //内容标签的修改
    public function labelSubmit(Request $request)
    {
        $param = $request->all();
        $noteId = $param['note_id'] ?? 0;
        $firstId = $param['first_id'] ?? 0;
        $secondId = $param['second_id'] ?? [];

        if (empty($noteId) || empty($firstId)) {
            return response()->json([
                'code' => 0,
                'msg' => '参数不能为空'
            ]);
        }
        $result = ContentRelatedLabel::changeNoteLabel($noteId, $firstId, $secondId, Admin::user()->id);
        return response()->json([
            'code' => 1,
            'msg' => 'ok',
            'data' => $result
        ]);
    }
    private function _getVideoExpand($videoInfo, $wikiInfos)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));

        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }
    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }
    private function labelScript()
    {
        $prefix = request()->url();
        return <<<SCRIPT
function loadScript(src, callback) {  
var script = document.createElement("script");  
  
if(script.addEventListener)  
script.addEventListener("load", callback, false);  
else if(script.attachEvent)  
script.attachEvent("onreadystatechange",  
function() { loadScript.callbackIE(callback); });  
  
script.src = src;  
document.getElementsByTagName("head")[0].appendChild(script);  
}  
loadScript.callbackIE = function(callback) {  
var target = window.event.srcElement;  
if(target.readyState == "loaded")  
callback.call(target);  
};  
  
// load 30k script.  
// Listener.cleanUp is defined at the bottom of drag.js  
callback = function() {  

notePicTag.init({
            selectRequestUrl: '{$prefix}/content/labelList',
            submitRequestUrl: '{$prefix}/content/labelSubmit',
            rootNodeId: 'content-label'
        }); 
};  

loadScript("/vendor/js/frieza-fe/notePicTag.js", callback);
SCRIPT;
    }

    private function _getPicExpand($picInfos, $wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }
    private function _getWikiExpand($wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($wikiInfo) {
            return "<div style='display:inline-block;margin:3px;width:220px;height:220px;'>" .
                "<img src='" . $wikiInfo['cover_img'] . "' height='200' class='img' /><br/>" .
                "<a href='https://beerus.haohaozhu.me/admin/wiki/admList/{$wikiInfo['id']}/edit' target='_blank' >{$wikiInfo['basic_title']}</a>" .
                "</div>";

        }, (array)$wikiInfos)));
        $box = new Box('wiki信息');
        $box->solid()->content($row->render());
        return $box->render();
    }
    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    public function tagSearch(Request $request)
    {
        $rs = [];
        $match = [];
        $search = $request->get('q');
        $type = $request->get('type');

        if($type == 1) {
            //中心词
            $center_pinyin_arr = [];
            if(file_exists(self::CENTER_FILE_2_0)) {
                $center_pinyin_arr = json_decode(file_get_contents(self::CENTER_FILE_2_0), true);
            }
            foreach($center_pinyin_arr as $index=>$tag) {
                if(stripos($index, $search, 0) === 0) {
                    $rs[$index]['id'] = $index;
                    $rs[$index]['text'] = $tag;
                }
            }
        } else if($type == 2){
            //属性
            $attr_pinyin_arr = [];
            if(file_exists(self::ATTR_FILE_2_0)) {
                $attr_pinyin_arr = json_decode(file_get_contents(self::ATTR_FILE_2_0), true);
            }
            foreach ($attr_pinyin_arr as $index => $tag) {
                if (stripos($index, $search, 0) === 0) {
                    $rs[$index]['id'] = $index;
                    $rs[$index]['text'] = $tag;
                }
            }
        }
        if($rs && is_array($rs)) {
            if(isset($rs[$search])) {
                $match = $rs[$search];
                unset($rs[$search]);
                $rs = array_values(array_merge([$match], array_values($rs)));
            }
        }

        $result = [
            'total' => count($rs),
            'per_page' => count($rs),
            'current_page' => 1,
            'last_page' => 1,
            'next_page_url' => null,
            'prev_page_url' => null,
            'from' => 1,
            'to' => count($rs),
            'data' => array_values($rs)
        ];

        return json_encode($result);

    }

    //获取不需要看pic数的admin_id
    public function getAdminIdFilterPicNum()
    {
        $admin_ids = [];
        $filter_pic_num_file = self::FILTER_ADMIN_ID_FOR_PIC_NUM;
        if(file_exists($filter_pic_num_file)) {
            $admin_ids = explode(PHP_EOL, file_get_contents($filter_pic_num_file));
        }
        $admin_ids = array_filter($admin_ids);
        return $admin_ids;
    }

    //打标签提交
    public function submitTags(Request $request)
    {
        $admin_tag_new = '';
        try {
            $request = $request->all();
            $center_pinyin_arr = [];
            $attr_pinyin_arr = [];
            //参数
            $note_id = $request['note_id'];
            $pic_id = $request['pic_id'];
            $tags_json = $request['tags_json'];
            $recommend_tags = $request['recommend_tags'];
            if(file_exists(self::CENTER_FILE_2_0)) {
                $center_pinyin_arr = (array) json_decode(file_get_contents(self::CENTER_FILE_2_0), true);
            }
            if(file_exists(self::ATTR_FILE_2_0)) {
                $attr_pinyin_arr = (array) json_decode(file_get_contents(self::ATTR_FILE_2_0), true);
            }
            $filter_tags = [];
            //后端数据校验
            $tags_arr = json_decode($tags_json, true);
            if($tags_arr && is_array($tags_arr)) {
                foreach($tags_arr as $k=>&$tag_info) {
                    $attrs_arr_check = [];
                    if(isset($tag_info['name']) && !in_array($tag_info['name'], $center_pinyin_arr)) {
                        $filter_tags[] = $tag_info['name'];
                        unset($tags_arr[$k]);
                        continue;
                    }

                    if(isset($tag_info['attrs']) && trim($tag_info['attrs'])) {
                        $attrs_arr = explode(',', $tag_info['attrs']);
                        if($attrs_arr && is_array($attrs_arr)) {
                            foreach($attrs_arr as $index=>$attr) {
                                if(in_array($attr, $attr_pinyin_arr)) {
                                    $attrs_arr_check[] = $attr;
                                } else {
                                    $filter_tags[] = $attr;
                                }
                            }
                            $tag_info['attrs'] = implode(',', array_unique($attrs_arr_check));
                        }
                    }

                }
            }

            $note_tags = AdmPicTags::getRelInfosByIds([$note_id]);

            $data['tags_json'] = json_encode(array_values($tags_arr), JSON_UNESCAPED_UNICODE);
            $data['admin_id'] = Admin::user()->id;
            $tags_old_arr = [];
            if($note_tags[$pic_id] && is_array($note_tags[$pic_id])) {
                //旧tags_json
                $tags_arr_old = json_decode($note_tags[$pic_id]['tags_json'], true);
                $tags_old = '';
                if($tags_arr_old && is_array($tags_arr_old)) {
                    foreach($tags_arr_old as $tag_info) {
                        $tags_old.=$tag_info['name'].','.$tag_info['attrs'].',';
                    }
                    $tags_old_arr = array_filter(array_unique(explode(',', $tags_old)));
                }

                $data['edittime'] = time();
                $result = AdmPicTags::editByPicAndNote($pic_id, $note_id, $data);
                if (!$result) {
                    throw new \Exception('note_id:'.$note_id.' pic_id:'.$pic_id.'修改至adm_pic_tag表失败');
                }
            } else {
                $data['note_id'] = $note_id;
                $data['pic_id'] = $pic_id;
                $data['addtime'] = time();
                $result = AdmPicTags::add($data);
                if (!$result) {
                    throw new \Exception('note_id:'.$note_id.' pic_id:'.$pic_id.'添加至adm_pic_tag表失败');
                }
            }
            if($result) {
                //更新photo表
                $photo_info = dbPhoto::getPhoto($note_id);
                $admin_tag_old = [];
                if($photo_info && is_array($photo_info)) {
                    $admin_tag_old = array_filter(explode(',', $photo_info['admin_tag']));
                }
                $tags_arr = json_decode($tags_json, true);
                $admin_tag_new = '';
                if($tags_arr && is_array($tags_arr)) {
                    foreach($tags_arr as $tag_info) {
                        $admin_tag_new.=$tag_info['name'].','.$tag_info['attrs'].',';
                    }
                    $admin_tag_new = array_filter(array_unique(explode(',', $admin_tag_new)));

                    //取差集
                    $diff = array_values(array_diff($tags_old_arr, $admin_tag_new));
                    $admin_tag_new = array_filter(array_unique(array_merge($admin_tag_old, $admin_tag_new)));
                    foreach($admin_tag_new as $k=>$tag) {
                        foreach($diff as $diff_tag) {
                            if(trim($tag) == trim($diff_tag)) {
                                unset($admin_tag_new[$k]);
                            }
                        }

                    }
                    $admin_tag_new = implode(',', $admin_tag_new);
                    $photo_data['admin_tag'] = (string) $admin_tag_new;
                    $photo_data['edittime'] = time();
                    $photo_data['status'] = dbPhoto::STATUS_SUCCESS;
                    dbPhoto::updatePhotoById($note_id, $photo_data);
                } else {
                    if($tags_old_arr && is_array($tags_old_arr) && $admin_tag_old && is_array($admin_tag_old)) {
                        $diff = array_values(array_diff($tags_old_arr, []));
                        foreach($admin_tag_old as $k=>$tag) {
                            foreach($diff as $diff_tag) {
                                if(trim($tag) == trim($diff_tag)) {
                                    unset($admin_tag_old[$k]);
                                }
                            }
                        }
                        $admin_tag_new = implode(',', $admin_tag_old);
                        $photo_data['admin_tag'] = (string) $admin_tag_new;
                        $photo_data['edittime'] = time();
                        $photo_data['status'] = dbPhoto::STATUS_SUCCESS;
                        dbPhoto::updatePhotoById($note_id, $photo_data);
                    }
                }

                //更新算法标签表
                $predicts = PredictImages::getRobotLabelForCheck($pic_id);
                if($predicts && is_array($predicts)) {
                    foreach($predicts as $predict) {
                        if(in_array($predict['predict_label'], explode(',', $recommend_tags))) {
                            PredictImages::updateCheck($predict['id'], $predict['predict_label']);
                        }
                    }
                }

                //更新分包表
                $packageRelated = PackageRelatedInfo::getPicInfo($pic_id, Admin::user()->id);
                if($packageRelated && is_array($packageRelated)) {
                    $package_id = $packageRelated['package_id'];
                    $package_info = UserPackage::getPackageClaimant($package_id);
                    if(in_array($package_info['check_status'], UserPackage::OPERATE_STATUS)) {
                        $admin_tags = '';
                        if($tags_arr && is_array($tags_arr)) {
                            foreach ($tags_arr as $tag_info) {
                                $admin_tags .= $tag_info['name'] . ',' . $tag_info['attrs'] . ',';
                            }
                            $admin_tags = array_filter(explode(',', $admin_tags));
                            $count = count($admin_tags);
                            $admin_tags_str = implode(',', $admin_tags);
                            $dat = [
                                "edittime" => date('Y-m-d H:i:s', time()),
                                "tags" => trim($admin_tags_str),
                                "tags_num" => $count
                            ];
                            $package_result = PackageRelatedInfo::updatePackageBaseInfo($packageRelated['id'], $dat);
                            if(!$package_result) {
                                throw new \Exception('note_id:'.$note_id.' pic_id:'.$pic_id.'修改至relatedPackage表失败,数据为'.json_encode($dat, JSON_UNESCAPED_UNICODE));
                            }
                        }
                    }
                }
            }


            // 添加到队列，更新搜索图片
            CommunityQueue::insertQueue('queue/photo/editphoto', [
                'photo_id' => $note_id
            ], CommunityQueue::QUEUE_COMMUNITY);

            $rs = [
                'code' => 1,
                'data' => 'success',
                //'filter' => (array)$filter_tags,
                'tags_json' => $data['tags_json'],
                'admin_tag' => $admin_tag_new
            ];

            Log::info('操作时间：'.date('Y-m-d H:i:s', time()) . ' 操作人ID：'.$data['admin_id'] . ' note_id：' . $note_id . ' pic_id：' . $pic_id . ' 标签参数：' . $tags_json . ' 返回值：' . json_encode($rs, JSON_UNESCAPED_UNICODE));

            return json_encode($rs, JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            Log::debug($e->getCode() . '--' . $e->getMessage());
            return [
                "code" => $e->getCode(),
                "data" => $e->getMessage()
            ];

        }

    }


    public function editMould(Request $request, $id)
    {
        $request = $request->all();
        $moulds = '';
        if(file_exists(self::TAG_MOULDS)) {
            $moulds = file_get_contents(self::TAG_MOULDS);
        }
        $moulds = ['id'=>$id, 'moulds'=>$moulds];
        $form = new Form($moulds);
        $form->hidden('id');
        $form->textarea('moulds', '标签模板')->rows(10);
        $form->action('/admin/photo/mouldList/'.$id.'/save');
        return $form->render();

    }

    public function submitMould(Request $request)
    {
        $request = $request->all();

        $moulds = $request['moulds'];
        if(json_decode($moulds, true) && is_array(json_decode($moulds, true))) {

            if(file_exists(self::TAG_MOULDS)) {
                file_put_contents(self::TAG_MOULDS, $moulds);
                $success = new MessageBag([
                    'title' => '提交成功'
                ]);
                return redirect('/admin/photo/mouldList')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '提交失败，格式错误'
                ]);
                return redirect('/admin/photo/mouldList')->with(compact('error'));
            }

        } else {
            $error = new MessageBag([
                'title' => '提交失败，格式错误'
            ]);
            return redirect('/admin/photo/mouldList')->with(compact('error'));
        }
    }

    //note详情页
    public function detail(Request $request, Content $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('note详情')
            ->body($this->listDetail($request, $id));
    }

    public function listDetail($request, $id)
    {
        $photo_info = (array)Photos::getPhotoInfos([$id], 0);
        $photo_info = array_values($photo_info)[0];
        $stickers = PicStickers::getStickersByNoteId($id);
        $user_type = AdmUserType::getByUid($photo_info['user_info']['uid']);
        $photo_info['photo_info']['user_info']['identify_remark'] = $user_type;
        $photo_info['photo_info']['stickers'] = $stickers;
        $photo_info['expand'] = $this->_getPhotoExpand(['info'=>$photo_info['photo_info']['image_list']]);
        $gridModel = new pGridDataModel([$photo_info], 1, [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableActions();
            $grid->column('photo_info', '图片信息')->display(function() {
                $stickers_str = '';
                $id = "<strong>id：</strong>".$this->photo_info['id']."<br>";
                $remark = "<strong>图说：</strong>".$this->photo_info['remark']."<br>";
                $addtime = "<strong>发布时间：</strong>".date('Y-m-d H:i:s', $this->photo_info['addtime'])."<br>";
                $admin_tag = "<strong>标签：</strong>".$this->photo_info['admin_tag']."<br>";
                $stickers = $this->photo_info['stickers'];
                if($stickers && is_array($stickers)) {
                    foreach($stickers as $k=>$sticker_info) {
                        $sticker_arr = json_decode($sticker_info['img_tags'], true);
                        $sticker_arr = array_column($sticker_arr, 'user_tag');
                        $stickers_str = $stickers_str.','.implode(',', $sticker_arr);
                    }
                }


                return $id.$remark.$addtime.$admin_tag."<strong>点图标签：</strong>".$stickers_str."<br>";
            })->width(400);
            $grid->column('user_info', '用户信息')->display(function() {
                $nick = "<strong>昵称：</strong>".$this->user_info['nick']."<br>";
                $uid = "<strong>uid：</strong>".$this->user_info['uid']."<br>";
                $type = "<strong>用户身份：</strong>".Member::$typeDesc[$this->user_info['type']]."<br>";
                $identify = "<strong>运营备注：</strong>".$this->user_info['identify_remark']."<br>";
                return $nick.$uid.$type.$identify;
            })->width(400);
            $grid->column('info', 'pic信息')->expand(function($model) {
                return $this->expand;
            }, true)->width(100);
        });

        return $listGrid->render();

    }

    public function _getPhotoExpand($picArr)
    {
        $row = new Row();
        if ($picArr) {
            $GirdModel = new pGridDataModel($picArr, 1, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableActions();
            $grid->disableExport();
            $grid->column('info', 'pic信息')->display(function() {
                $infos = json_decode($this, true);
                if($infos && is_array($infos)) {
                    $pic = '';
                    foreach($infos as $pic_info) {
                        $pic.= "<div style='display:inline-block;margin:3px;height:320px;'>"."<img src='".$pic_info['pic_url']."' height='300' class='img' />"."<br>".$pic_info['pic_id']."</div>";
                    }
                    return "<div style='width:100%;height:330px;overflow-y: scroll;'>".$pic."</div>";
                }

            });

            $grid->disablePagination();
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
            });
            $row->column('12', $grid);
            return $row->render();
        }
        return '';
    }

    //算法文本标签格式化
    public function formatTags($tag_infos)
    {
        $rs = [];
        if($tag_infos && is_array($tag_infos)) {
            $all_tags = dbTag::getAllByWhere([
                "tag_status" => dbTag::TAG_STATUS_ON
            ]);
            $center_arr = array_column($this->getTree($all_tags, dbTag::TAG_COMMUNITY), 'tag');
            $attr_arr = dbTag::getAttrTags();
            $center_arr = array_diff($center_arr, $attr_arr);
            foreach($tag_infos as $tag_info) {
                if(in_array($tag_info['keyword'], $center_arr)) {
                    $rs[$tag_info['obj_id']]['centers'][] = $tag_info['keyword'];
                }
            }
            if($rs && is_array($rs)) {
                foreach($rs as $k=>$tags) {
                    $rs[$k]['centers'] = implode(',', (array) $tags['centers']);
                    $rs[$k]['attrs'] = '';
                }
            }
        }
        return $rs;
    }

    //递归排序树
    public function getTree($tags, $pid, $level = 1)
    {
        static $list = [];
        if($tags && is_array($tags)) {
            $value['tag_levels'] = '';
            foreach ($tags as $key => $value) {
                if ($value['parent_id'] == $pid) {
                    $value['deep'] = $level;
                    //把数组放到list中
                    $list[] = $value;
                    unset($tags[$key]);
                    $this->getTree($tags, $value['id'], $level + 1);
                }
            }
        }

        return $list;
    }

}